﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Animation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using TheVerge.Base;
using TheVerge.Base.Models;
using TheVerge.Base.Platform;
using System.Windows.Data;

namespace TheVerge.Phone.Controls {

	public partial class NewsControl : UserControl {

		#region Private Variables
		private ProgressIndicator loadingIndicator;
		#endregion

		public NewsControl() {
			InitializeComponent();
            aec1.ArticleLoaded += new EventHandler(Article_Loaded);
		}

		#region Public

		public bool IsArticleVisible { get { return aec1.Opacity > 0; } }

		public void HideArticle() {

			if (aec1.IsOverlayVisible)
			{
				aec1.HideOverlay();
			}
			else
			{
				loadingIndicator.IsVisible = false;
				aec1.Hide();
			}
		}

		public void InitArticleViewer() {
			aec1.InitArticleViewer(ActualWidth, ActualHeight);
		}

        public void RefreshActiveArticle()
        {
            if (aec1.IsVisible)
                aec1.Refresh();
        }

		public void SetPage(PhoneApplicationPage page) {
			loadingIndicator = new ProgressIndicator();
			loadingIndicator.IsIndeterminate = true;
			loadingIndicator.Text = @"Loading . . .";
			loadingIndicator.IsVisible = false;
			SystemTray.SetProgressIndicator(page, loadingIndicator);

			page.Loaded += (s, e) => InitArticleViewer();
			page.OrientationChanged += (s, e) => InitArticleViewer();
		}

		#endregion

		#region Event Handlers

		private void Article_Click(object sender, RoutedEventArgs e) {
			var fe = sender as FrameworkElement;
			ShowArticle(fe.DataContext as ArticleEntry);
		}

		private void Article_Loaded(object sender, EventArgs e) {
			loadingIndicator.IsVisible = false;
		}

		private void OnAPIError(Exception exp) {
			Factory.UI.Invoke(() => MessageBox.Show(exp.Message));
		}

		private void OnAPIResult(APIResponse<ArticleEntry> result, InfiniteScroller ic) {
			if (result != null)
				Factory.UI.Invoke(() =>
				{
					ic.ItemsSource = result.Entries;
				});
		}

		private void thePiv_SelectionChanged(object sender, SelectionChangedEventArgs e) {
			if (thePiv.SelectedItem != null) {
                var vm = thePiv.SelectedItem as VMEntries<ArticleEntry>;
				if (vm != null && vm.ItemsCount == 0)
					vm.Refresh();
			}
		}

		#endregion

		#region Helper Methods
		private void ShowArticle(ArticleEntry entry) {
			aec1.LoadEntry(entry);

			loadingIndicator.IsVisible = true;
		}
		#endregion
    }
}
